package com.cs.deviceManager.service.impl;

import com.cs.deviceManager.domain.DevDevice;
import com.cs.deviceManager.mapper.DevDeviceMapper;
import com.cs.deviceManager.mqtt.MqttUtil;
import com.cs.deviceManager.service.IDevDeviceService;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 设备信息Service业务层处理
 *
 * @author zizige
 * @date 2025-06-30
 */
@Service
public class DevDeviceServiceImpl implements IDevDeviceService {
    @Resource
    private DevDeviceMapper devDeviceMapper;

    @Value("${mqtt.client-id:device-status-listener}")
    private String clientId;

    /**
     * 查询设备信息
     *
     * @param devId 设备信息主键
     * @return 设备信息
     */
    @Override
    public DevDevice selectDevDeviceByDevId(Long devId) {
        return devDeviceMapper.selectDevDeviceByDevId(devId);
    }

    /**
     * 查询设备信息列表
     *
     * @param devDevice 设备信息
     * @return 设备信息
     */
    @Override
    public List<DevDevice> selectDevDeviceList(DevDevice devDevice) {
        return devDeviceMapper.selectDevDeviceList(devDevice);
    }

    /**
     * 新增设备信息
     *
     * @param devDevice 设备信息
     * @return 结果
     */
    @Override
    public int insertDevDevice(DevDevice devDevice) {
        devDevice.setCreateTime(DateUtils.getNowDate());
        int result = devDeviceMapper.insertDevDevice(devDevice);

        // 如果设备有订阅主题，则添加MQTT订阅
        if (result > 0 && devDevice.getSubscribe() != null && !devDevice.getSubscribe().isEmpty()) {
            // 注意：这里需要获取设备事件处理器，但因为是不同模块，暂时不实现
            // 在实际应用中，可能需要通过事件或消息机制通知MQTT模块进行订阅
            MqttUtil.subscribe(clientId, devDevice.getSubscribe(), null);
        }

        return result;
    }

    /**
     * 修改设备信息
     * @param devDevice 设备信息
     * @return 结果
     */
    @Override
    public int updateDevDevice(DevDevice devDevice) {
        // 获取更新前的设备信息
        DevDevice oldDevice = devDeviceMapper.selectDevDeviceByDevId(devDevice.getDevId());

        devDevice.setUpdateTime(DateUtils.getNowDate());
        int result = devDeviceMapper.updateDevDevice(devDevice);

        // 如果更新成功且订阅主题有变化，则更新MQTT订阅
        if (result > 0 && oldDevice != null) {
            String oldSubscribe = oldDevice.getSubscribe();
            String newSubscribe = devDevice.getSubscribe();

            // 检查订阅主题是否有变化
            boolean subscribeChanged = oldSubscribe == null && newSubscribe != null || oldSubscribe != null && !oldSubscribe.equals(newSubscribe);

            if (subscribeChanged) {
                // 取消旧的订阅（如果存在）
                if (oldSubscribe != null && !oldSubscribe.isEmpty()) {
                    MqttUtil.unsubscribe(clientId, oldSubscribe);
                }

                // 添加新的订阅（如果存在）
                if (newSubscribe != null && !newSubscribe.isEmpty()) {
                    MqttUtil.subscribe(clientId, newSubscribe, null);
                }
            }
        }

        return result;
    }

    /**
     * 批量删除设备信息
     *
     * @param devIds 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDevDeviceByDevIds(String devIds) {
        // 先获取要删除的设备信息，以便取消MQTT订阅
        String[] devIdArray = Convert.toStrArray(devIds);
        for (String devId : devIdArray) {
            DevDevice device = devDeviceMapper.selectDevDeviceByDevId(Long.valueOf(devId));
            if (device != null && device.getSubscribe() != null && !device.getSubscribe().isEmpty()) {
                MqttUtil.unsubscribe(clientId, device.getSubscribe());
            }
        }

        return devDeviceMapper.deleteDevDeviceByDevIds(devIdArray);
    }

    /**
     * 删除设备信息信息
     *
     * @param devId 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDevDeviceByDevId(Long devId) {
        // 先获取要删除的设备信息，以便取消MQTT订阅
        DevDevice device = devDeviceMapper.selectDevDeviceByDevId(devId);
        if (device != null && device.getSubscribe() != null && !device.getSubscribe().isEmpty()) {
            MqttUtil.unsubscribe(clientId, device.getSubscribe());
        }

        return devDeviceMapper.deleteDevDeviceByDevId(devId);
    }

    @Override
    public List<DevDevice> selectUnboundDevices() {
        return devDeviceMapper.selectUnboundDevices();
    }

    @Override
    public List<DevDevice> selectNearbyDevices(java.math.BigDecimal latitude, java.math.BigDecimal longitude) {
        return devDeviceMapper.selectNearbyDevices(latitude, longitude, 100);
    }

    /**
     * 解除设备绑定，清空设备经纬度
     *
     * @param devId 设备ID
     * @return 影响行数
     */
    @Override
    public int unbindDevice(Long devId) {
        return devDeviceMapper.unbindDevice(devId);
    }

    /**
     * 更新设备状态
     * @param devNumber 设备编号
     * @param isOnline 设备状态
     */
    @Override
    public void updateStatus(String devNumber, boolean isOnline) {
        DevDevice dev = devDeviceMapper.selectDevDeviceByDevNumber(devNumber);
        if(dev == null)
        {
            return;
        }
        dev.setStatus(isOnline ? "1" : "0");
        updateDevDevice(dev);

    }
    
    @Override
    public List<DevDevice> selectActiveDevices() {
        return devDeviceMapper.selectActiveDevices();
    }
}
